package com.kuang.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * Mybatis工具类
 *
 * @author amx
 * @create 2020/9/21 20:03
 */
public class MybatisUtils {
	private static SqlSessionFactory factory;

	// 静态代码块保证初始类即加载
	static {
		try {
			// 1. 获取SQLSessionFactory对象
			String resource = "mybatis-config.xml";
			InputStream is = Resources.getResourceAsStream(resource);
			factory = new SqlSessionFactoryBuilder().build(is);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 生成自动提交事务的SqlSession
	 *
	 * @return SqlSession
	 */
	public static SqlSession getSqlSession() {
		return factory.openSession(true);
	}


}
